package com.poi.exp.writer;

import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.poi.exp.domain.BaseModel;
import com.poi.exp.domain.CellModelVO;
import com.poi.exp.domain.RowModelVO;
import com.poi.exp.domain.SingleRowModelVO;
import com.poi.util.ExcelOneSheetUtil;
import com.poi.util.ExcelOperationUtil;
import com.poi.util.PoiContextUtil;
import com.poi.util.RegexUtils;

/**
 * 默认的行处理器。单元格内容中含有${key}的进行替换，否则不处理
 * 
 * @author wzy
 */
public class DefaultRowWriter implements RowWriter {
	private static final Logger log = LoggerFactory.getLogger(DefaultRowWriter.class);

	public static class SINGLE {
		public static DefaultRowWriter INSTANCE = new DefaultRowWriter();
	}

	@Override
	public void writerRow(RowModelVO rowModelVO, Sheet sheet) {
		SingleRowModelVO singleRow = (SingleRowModelVO) rowModelVO;
		List<BaseModel> cellList = singleRow.getCellList();
		Row writerRow = sheet.createRow(PoiContextUtil.getContext().getWriterRowNum());
		//单元格合并
		//ExcelOneSheetUtil.copyMergeRegion(singleRow.getRow().getSheet(),singleRow.getRow().getRowNum(), PoiContextUtil.getContext().getWriterRowNum());
		for (int i = 0, l = cellList.size(); i < l; i++) {
			BaseModel baseModel = cellList.get(i);
			if (baseModel instanceof CellModelVO) {
				CellModelVO cellVO = (CellModelVO) baseModel;
				if (null != cellVO.getCell()) {
					Cell createCell = writerRow.createCell(cellVO.getCell().getColumnIndex());
					//复制样式
					ExcelOperationUtil.copyCell(cellVO.getCell(),createCell);
					String expression = cellVO.getExpression();
					// log.info("解析rowIndex={},columnIndex={}", cell.getRowIndex(),
					// cell.getColumnIndex());
					String resolvedContent = RegexUtils.resolve(expression);
					createCell.setCellValue(resolvedContent);
					//记录是否需要合并单元格
					ExcelOneSheetUtil.isNeedMergen(cellVO.getCell(),createCell);
				}
			}
		}
		PoiContextUtil.getContext().setWriterRowNum(PoiContextUtil.getContext().getWriterRowNum() + 1);
	}

	@Override
	public int support(RowModelVO row) {
		return 0;
	}
}
